<template>
	<div class="app-container">
		<div ref="box1" class="flex-center margin-bottom-10">
			<el-radio-group v-model="searchParams.serviceState" size="medium" class="item-gap" @change="onStateChange">
				<el-radio-button v-for="item in foreSpinPlanStateList" :key="item.id" :label="item.id">
					<el-badge v-if="item.id <= 2 && item.count > 0" :value="item.count" :max="99">
						<span class="margin-right-20">{{ item.name }}</span>
					</el-badge>
					<div v-else class="margin-right-10" style="padding-bottom: 2px;">{{ item.name }}</div>
				</el-radio-button>
			</el-radio-group>
		</div>
		<jk-operation-card ref="box2" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<jk-add-button :permission-prefix="prefix" class="margin-5-0 item-gap" @click="onAddBtn"></jk-add-button>
					<!--<jk-report-button :permission-prefix="prefix" class="margin-5-0" :loading="exportLoading" @click="onReportBtn"></jk-report-button>-->
				</div>
				<div class="flex-end-center-wrap">
					<jk-select v-model="searchParams.workshopId" :option-list="workshopList" placeholder="区域" :clearable="false" size="small" class="search-bar-item-size2 margin-5-0 item-gap" @on-enter="onSearchBtn"></jk-select>
					<jk-search-input v-model="searchParams.productOrderCode" placeholder="生产订单号" size="small" class="search-bar-item-code margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-input v-model="searchParams.productName" placeholder="品种名称" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-input v-model="searchParams.batchCode" placeholder="批号" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-input v-model="searchParams.code" placeholder="单据编号" size="small" class="search-bar-item-code margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table :loading="tableLoading" :data="tableData" :height="tableHeight + 10">
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<jk-state-bar v-if="item.keyName === 'serviceState'" :state="scope.row.serviceState" :state-list="foreSpinPlanStateList"></jk-state-bar>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" fixed="right" :width="220">
					<template slot-scope="scope">
						<div class="flex-center">
							<div class="item-gap" @click="onReleaseBtn(scope.row)"><el-button :disabled="scope.row.serviceState !== 0" size="mini" type="primary">下达</el-button></div>
							<el-button :disabled="scope.row.serviceState === 3" class="item-gap" size="mini" type="primary" @click="onEditBtn(scope.row)">编辑</el-button>
							<el-dropdown trigger="click" @command="onDropdownChange($event, scope.row)">
								<el-button type="primary" size="mini" class="el-dropdown-link">
									更多<i class="el-icon-arrow-down el-icon--right"></i>
								</el-button>
								<el-dropdown-menu slot="dropdown">
									<el-dropdown-item
										v-for="(item) in dropdownOption"
										:key="item.code"
										:command="item.code"
										:divided="item.divided"
										:disabled="item.allowState || item.allowState === 0 ? scope.row.serviceState !== item.allowState : false"
										:style="{
											'display': !item.isShow ? 'none' : 'block',
											'text-decoration': getPermission([`${prefix}:${item.permissionName}`]) ? '' : 'line-through'
										}"
									>
										<span :class="`${item.icon} item-gap`"></span>
										<span>{{ item.name }}</span>
									</el-dropdown-item>
								</el-dropdown-menu>
							</el-dropdown>
						</div>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box3" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, tipsBar } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../../mixins/getMenuColumn';
    import handlerCache from '../../../../mixins/handler-cache';
    import {
        qslProductionClearComplete,
        qslProductionClearRelease, qslProductionComplete,
        qslProductionDelete, qslProductionGetStateCount,
        qslProductionPage,
        qslProductionRelease
    } from '../../../../api/production/qslb';
    import permissionMixin from '../../../../mixins/permission-mixin';
    import { foreSpinPlanStateList } from '../../../../utils/jk/status-option-list';
    export default {
        name: 'ForeSpinningPlan',
        components: {
        },
        mixins: [calHeight, getMenuColumn, handlerCache, permissionMixin],
        data() {
            return {
                prefix: 'production:plan',
                apiItem: {
                    'page': qslProductionPage,
                    'delete': qslProductionDelete,
                    'exportExcel': null
                },
                foreSpinPlanStateList: foreSpinPlanStateList,
                dataId: null,
                workshopList: [],
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                totalCount: null,
                dropdownOption: [
                    { code: 'QUERY', name: '详情', isShow: true, permissionName: 'query', icon: 'el-icon-view', allowState: null, api: null },
                    { code: 'CANCEL_CLOSE', name: '撤销下达', permissionName: 'update', isShow: true, icon: 'el-icon-circle-close', allowState: 1, api: qslProductionClearRelease },
                    { code: 'FINISH', name: '完成生产', permissionName: 'update', isShow: true, icon: 'el-icon-circle-close', allowState: 2, api: qslProductionComplete },
                    { code: 'CANCEL_FINISH', name: '撤销完成', permissionName: 'update', isShow: true, icon: 'el-icon-circle-close', allowState: 3, api: qslProductionClearComplete },
                    { code: 'DELETE', name: '删除', isShow: true, permissionName: 'delete', icon: 'el-icon-delete', allowState: 0, api: qslProductionDelete }
                ],
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    nameOrCode: '',
                    batchCode: '',
                    productOrderCode: '',
                    serviceState: 1,
                    workshopId: null
                }
            };
        },
        methods: {
            onStateChange() {
                this.searchParams.pageNo = 1;
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            onDropdownChange(type, { id }) {
                const optionItem = this.dropdownOption.find(x => x.code === type);
                if (this.getPermission([`${this.prefix}:${optionItem.permissionName}`])) {
                    if (optionItem) {
                        if (optionItem.code === 'QUERY') {
                            this.onDetailBtn({ id });
                        } else {
                            this.$confirm(`确定"${optionItem.name}"吗？`, '提示', { type: 'warning' }).then(() => {
                                optionItem.api({ id: id }).then(res => {
                                    if (res.data.status === 200) {
                                        this.getListRequest();
                                    }
                                });
                            }).catch(() => {});
                        }
                    }
                } else {
                    tipsBar(this, 'custom', 'warning', '无操作权限!');
                }
            },
            onReleaseBtn({ id }) {
                this.$confirm(`确定"下达"吗？`, '提示', { type: 'warning' }).then(() => {
                    qslProductionRelease({ id }).then(res => {
                        if (res.data.status === 200) {
                            this.getListRequest();
                        }
                    });
                }).catch(() => {});
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            getStateBarCountRequest() {
                return qslProductionGetStateCount({
                    workshopId: this.searchParams.workshopId
                }).then(res => {
                    if (res.data.status === 200) {
                        this.foreSpinPlanStateList = this.foreSpinPlanStateList.map(x => {
                            x.count = 0;
                            res.data.res.forEach(k => {
                                if (x.id === k.serviceState) {
                                    x.count = k.count;
                                }
                            });
                            return x;
                        });
                    } else {
                        this.foreSpinPlanStateList = this.foreSpinPlanStateList.map(x => {
                            x.count = 0;
                            return x;
                        });
                    }
                });
            },
            async getDependentData() {
                this.tableLoading = true;
                await this.getMenuColumnListRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            onDetailBtn(row) {
                this.dataId = row.id;
                this.$toOtherRouter({
                    name: 'detailForeSpinningPlan',
                    query: {
                        id: row.id
                    }
                });
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                const params = JSON.parse(JSON.stringify(this.searchParams));
                params.serviceStates = [params.serviceState];
                delete params.serviceState;
                return this.apiItem['page'](params).then(res => {
                    this.tableLoading = false;
                    this.getStateBarCountRequest();
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.totalCount = res.data.count;
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getListRequest();
            },
            /** 新增按钮操作 */
            onAddBtn() {
                this.$toOtherRouter({
                    name: 'addForeSpinningPlan',
                    query: {
                        workshopId: this.searchParams.workshopId
                    }
                });
            },
            /** 修改按钮操作 */
            onEditBtn(row) {
                this.dataId = row.id;
                this.$toOtherRouter({
                    name: 'editForeSpinningPlan',
                    query: {
                        id: row.id
                    }
                });
            },

            /** 删除按钮操作 */
            onDeleteBtn(row) {
                this.apiItem['delete']({ id: row.id }).then((res) => {
                    if (res.data.status === 200) {
                        this.getListRequest();
                        this.$tipsBar(this, 'delete');
                    }
                }).catch(() => {});
            },
            /** 导出按钮操作 */
            onReportBtn() {
                const params = { ...this.searchParams };
                params.pageNo = null;
                params.pageSize = null;
                this.$confirm('是否确认导出所有数据项?', { type: 'warning' }).then(() => {
                    this.exportLoading = true;
                    return this.apiItem['exportExcel'](params);
                }).then(res => {
                    if (res.data.status === 200) {
                        this.$download.excel(res, `${this.$route.meta.name}.xls`);
                        this.exportLoading = false;
                    }
                }).catch(() => {});
            }
        },
        mounted() {
            this.workshopList = this.$store.state.user.userWorkshop.workshopList;
            if (!this.searchParams.workshopId) {
                const workshopItem = this.workshopList.find(x => x.code === 'QF') || {};
                this.$set(this.searchParams, 'workshopId', workshopItem.id || this.$store.state.user.userWorkshop.defaultWorkshopId);
            }
            this.getDependentData();
        }
    };
</script>
